package com.tianji.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;

public class QRCodeGenerator {

    public static String generateQRCode(String text, String fileName) throws Exception {
        // 获取资源目录的绝对路径 (src/main/resources/qrcodes)
        Path resourceDirectory = Paths.get("src", "main", "resources", "qrcodes");
        File directory = resourceDirectory.toFile();

        // 如果目录不存在则创建
        if (!directory.exists()) {
            directory.mkdirs();
        }

        // 拼接二维码文件的完整路径
        String filePath = directory.getAbsolutePath() + File.separator + fileName;
        System.out.println("二维码生成路径：" + filePath);

        // 调用生成二维码的方法
        QRCodeGenerator.generateQRCodeImage(text, filePath, 300, 300);

        return filePath;
    }

    public static void generateQRCodeImage(String text, String filePath, int width, int height) throws Exception {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);

        Path path = Paths.get(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }
}
